package com.geek.jdbc.work2v2.pool;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class ThreadLocalByC3P0Utils {

    private static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");

    //线程变量
    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    //获取数据源的方法
    public static DataSource getDataSource() {
        return dataSource;
    }

    //获取连接的方法
    public static Connection getConnection() {
        Connection conn = tl.get();
        try{
            if (conn == null || conn.isClosed() ) {
                conn = dataSource.getConnection();
                tl.set(conn);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //归还连接的方法
    public static void close() {
        Connection conn = tl.get();
        try {
            if (conn != null && !conn.isClosed() ) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
